package site.user.action;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modules.recruit.entity.ApplyConfirm;
import modules.recruit.entity.ApplyDivide;
import modules.recruit.entity.ApplyFinance;
import modules.recruit.entity.ApplyManager;
import modules.recruit.entity.Region;
import modules.recruit.entity.RmProvince;
import modules.recruit.form.ApplyBgForm;
import modules.recruit.form.ApplyEquityForm;
import modules.recruit.form.ApplyFinanceForm;
import modules.recruit.form.ApplyPlanForm;
import modules.recruit.form.RegionForm;
import modules.recruit.service.ApplyConfirmService;
import modules.recruit.service.ApplyDivideService;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import site.user.form.ApplyBaseFormSite;

import com.guinea.core.service.EntityService;
import com.guinea.core.utils.CommonUtils;

import ex.recruit.service.ApplyManagerServiceEx;
import ex.recruit.service.RegionServiceEx;
import ex.recruit.service.RmProvinceServiceEx;

public class RegionActionSite extends ApplyCommonStep {
	private RegionServiceEx regionServiceEx;
	ApplyDivideService applyDivideService;
	RmProvinceServiceEx rmProvinceServiceEx;
	ApplyManagerServiceEx applyManagerServiceEx;
	ApplyConfirmService applyConfirmService;
	
	protected String serial;

	public EntityService getEntityService() {
		return regionServiceEx;
	}

	public RegionServiceEx getRegionServiceEx() {
		return regionServiceEx;
	}

	public void setRegionServiceEx(RegionServiceEx regionServiceEx) {
		this.regionServiceEx = regionServiceEx;
	}

	public ApplyDivideService getApplyDivideService() {
		return applyDivideService;
	}

	public void setApplyDivideService(ApplyDivideService applyDivideService) {
		this.applyDivideService = applyDivideService;
	}

	public RmProvinceServiceEx getRmProvinceServiceEx() {
		return rmProvinceServiceEx;
	}

	public void setRmProvinceServiceEx(RmProvinceServiceEx rmProvinceServiceEx) {
		this.rmProvinceServiceEx = rmProvinceServiceEx;
	}

	public ApplyManagerServiceEx getApplyManagerServiceEx() {
		return applyManagerServiceEx;
	}

	public void setApplyManagerServiceEx(ApplyManagerServiceEx applyManagerServiceEx) {
		this.applyManagerServiceEx = applyManagerServiceEx;
	}

	public ApplyConfirmService getApplyConfirmService() {
		return applyConfirmService;
	}

	public void setApplyConfirmService(ApplyConfirmService applyConfirmService) {
		this.applyConfirmService = applyConfirmService;
	}

	/**
	 * 初始化业务对象的函数.
	 */
	protected void findEntity(ActionForm form, HttpServletRequest request) {
		super.findEntity(form, request);
		serial = request.getParameter("serial");
		if (entity == null && applyBase != null && serial != null) {
			entity = getRegionServiceEx().getRegionByBaseSerial(applyBaseId,
					serial);
		}
		// 不是由ID参数得到的entity
		if (id == null && entity != null) {
			Region region = (Region) entity;
			RegionForm regionForm = (RegionForm) form;
			regionForm.setId(region.getId());
			id = region.getId();
		}
	}
	/**
	 * edit验证.
	 */
	public ActionForward editValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form, request);
		if (!validateApplyBase())
			return handleEntityMissing(mapping, form, request, response);
		
		if("1".equals(serial) && !CommonUtils.couldApplyBeModified(applyBase)){
			valid = false;
			saveDirectlyError(request, "该申请已提交，不能再修改。");
			return mapping.findForward(LIST);
		}
		return null;
	}
	
	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		if (entity == null)
			entity = getRegionServiceEx().getRegionByBaseSerial(applyBaseId,
					serial);

		bindForm(form, entity);
		RegionForm regionForm = (RegionForm) form;
		regionForm.setApplyBaseId(applyBaseId);

		return handleEdit(mapping, form, request, response);
	}

	protected void doInitEntity(HttpServletRequest request, ActionForm form) {
		super.doInitEntity(request, form);
		if (isCreateOperation) {
			Region region = (Region) entity;
			region.setBase(applyBase);
			entity = region;
		}
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doInitEntity(request, form);

		doSaveEntity(request, form);

		String direction = request.getParameter("direction");

		if (direction != null && direction.equals("last"))
			return new ActionForward(
					"/site/user/applyPlan.do?method=edit&applyBaseId="
							+ applyBaseId.toString(), true);
		else {
			saveMessage(request, "entity.saved");
			RegionForm regionForm = (RegionForm) form;
			regionForm.setId((Long) id);
			return handleEdit(mapping, form, request, response);
		}
	}

	/**
	 * 保存前的验证.
	 */
	public ActionForward submitValidator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		ActionForward forward = super.saveValidator(mapping, form, request, response); 
		if(forward != null) return forward;
		
		if (!validateForm(mapping, form, request))
			return handleFormErrors(mapping, form, request, response);
		
		return forward;
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward submit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doInitEntity(request, form);

		doSaveEntity(request, form);

		Region region = getRegionServiceEx().getRegionByBaseSerial(applyBaseId,
				"1");

		RegionForm regionForm = (RegionForm) form;
		ActionMapping stepMapping = new ActionMapping();
		
		//验证基本信息
		ApplyBaseFormSite applyBaseFormSite = new ApplyBaseFormSite();
		applyBaseFormSite.setServlet(regionForm.getServlet());
		bindForm(applyBaseFormSite, applyBase);
		ApplyManager applyManager = getApplyManagerServiceEx()
				.getManagerByBasePosition(applyBase.getId(), "1");
		if (applyManager != null) {
			applyBaseFormSite.setOwner(applyManager.getOwner());
			applyBaseFormSite.setCellphone(applyManager.getCellphone());
			applyBaseFormSite.setEmail(applyManager.getEmail());
		}
		stepMapping.setName("applyBaseFormSite");
		if(!validateForm(stepMapping, applyBaseFormSite, request)){
			saveErrors(request, formErrors);
			saveToken(request);
			return new ActionForward(
					"/site/user/apply.do?method=edit&id="
							+ applyBaseId.toString());
		}
		
		//验证股权信息
		ApplyEquityForm applyEquityForm = new ApplyEquityForm();
		applyEquityForm.setServlet(regionForm.getServlet());
		bindForm(applyEquityForm, applyBase.getEquity());
		stepMapping.setName("applyEquityForm");
		if(!validateForm(stepMapping, applyEquityForm, request)){
			saveErrors(request, formErrors);
			saveToken(request);
			return new ActionForward(
					"/site/user/applyEquity.do?method=edit&id="
							+ applyBaseId.toString());
		}
		
		//验证财务信息
		boolean isGood = true;
		ApplyFinance applyFinance = applyBase.getFinance();
		if(applyFinance == null || applyFinance.getHasReport() == null){
			saveDirectlyError(request, "您还没有填写财务信息");
			isGood = false;
		}
		if(isGood && applyFinance.getHasReport().equals("1")){
			ApplyFinanceForm applyFinanceForm = new ApplyFinanceForm();
			applyFinanceForm.setServlet(regionForm.getServlet());
			bindForm(applyFinanceForm, applyFinance);
			stepMapping.setName("applyFinanceForm");
			isGood = validateForm(stepMapping, applyFinanceForm, request);
			if(!isGood)saveErrors(request, formErrors);
		}
		if(!isGood){
			saveToken(request);
			return new ActionForward(
					"/site/user/applyFinance.do?method=edit&id="
							+ applyBaseId.toString());
		}
		
		//验证背景状况
		ApplyBgForm applyBgForm = new ApplyBgForm();
		applyBgForm.setServlet(regionForm.getServlet());
		bindForm(applyBgForm, applyBase.getBackground());
		stepMapping.setName("applyBgForm");
		if(!validateForm(stepMapping, applyBgForm, request)){
			saveToken(request);
			saveErrors(request, formErrors);
			return new ActionForward(
					"/site/user/applyBg.do?method=edit&applyBaseId="
							+ applyBaseId.toString());
		}
		
		//验证投资规划
		ApplyPlanForm applyPlanForm = new ApplyPlanForm();
		applyPlanForm.setServlet(regionForm.getServlet());
		bindForm(applyPlanForm, applyBase.getPlan());
		stepMapping.setName("applyPlanForm");
		if(!validateForm(stepMapping, applyPlanForm, request)){
			saveToken(request);
			saveErrors(request, formErrors);
			return new ActionForward(
					"/site/user/applyPlan.do?method=edit&applyBaseId="
							+ applyBaseId.toString());
		}
		
		
		applyBase.setSerial(getApplyBaseServiceEx().getSerial(region.getProvinceId()));
		applyBase.setSubmitDate(new Date());
		applyBase.setIsSubmitted("1");
		getApplyBaseServiceEx().update(applyBase);
		
		//自动分配
		ApplyDivide applyDivide = applyBase.getDivide();
		if(applyDivide == null){
			applyDivide = new ApplyDivide();
			applyDivide.setBase(applyBase);
			
			Set regions = applyBase.getRegion();
			String provinceId = region.getProvinceId();

			Long managerId = null;
			if(provinceId != null){
				List rmProvinces = getRmProvinceServiceEx().get();
				for (Iterator iter = rmProvinces.iterator(); iter.hasNext();) {
					RmProvince rmProvince = (RmProvince) iter.next();
					if(provinceId.equals(rmProvince.getProvinceId())){
						managerId = rmProvince.getOwner();
					}
				}
			}
			applyDivide.setOwner(managerId);
			getApplyDivideService().saveOrUpdate(applyDivide);
		}
		
		//如果是确认后修改，则申请确认步骤状态重置为2
		ApplyConfirm applyConfirm = applyBase.getConfirm();
		if(applyConfirm != null){
			applyConfirm.setTypeCode("2");
			getApplyConfirmService().update(applyConfirm);
		}
		
		//填写第2块场地
		Region region2 = getRegionServiceEx().getRegionByBaseSerial(applyBaseId,
		"2");
		if(region2 == null || "0".equals(region2.getStatus())){
			return new ActionForward(
					"/site/user/region.do?method=confirm&applyBaseId="
							+ applyBaseId.toString() + "&serial=2", true);
		}

		return new ActionForward(
				"/site/user/region.do?method=attach", true);
	}
	
	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward confirm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		initFirst(form, request);
		if (!validateApplyBase())
			return handleEntityMissing(mapping, form, request, response);
		
		Region region = getRegionServiceEx().getRegionByBaseSerial(applyBaseId,
		"1");
		request.setAttribute("region",region);

		return mapping.findForward("confirm");
	}

	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward attach(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward(SUCCESS);
	}


}
